package com.shujia

import scala.io.Source

object Code38Rank {
  def main(args: Array[String]): Unit = {
    /**
     * Rank:
     * 相同排名 名次一样 并且名次不连续
     */


    // 需求：按学生总分对班级数据进行排名
    val stuTotalScore: Map[String, Int] = Source
      .fromFile("scala_code/data/score.txt")
      .getLines()
      // 将读取到的每一行数据转换成List中的元素
      .toList
      .map(
        line => {
          val column: Array[String] = line.split(",")
          (column(0), column(1), column(2))
        }
      ).groupBy(
      _._1
    ).map(
      keyValue => {
        (keyValue._1, keyValue._2.map(_._3.toInt).sum)
      }
    )


    val stuInfoList: List[(String, String, Int, String, String)] = Source
      .fromFile("scala_code/data/students.txt")
      .getLines()
      // 将读取到的每一行数据转换成List中的元素
      .toList
      .map(
        (line: String) => {
          val colum: Array[String] = line.split(",")
          // (id,name,age,gender,clazz)
          //  Tuple相比较Array 其元素的数据类型可以多样
          (colum(0), colum(1), colum(2).toInt, colum(3), colum(4))
        }
      )


    val joinRes: List[(String, String, Int, String, String, Int)] = stuInfoList
      .map(
        oneStu => {
          val id: String = oneStu._1
          val score: Option[Int] = stuTotalScore.get(id)
          // id,name,age,gender,class,totalScore
          (oneStu._1, oneStu._2, oneStu._3, oneStu._4, oneStu._5, score.get)
        }
      )

    /**
     * pm = 1+1+1  score = 445  cnt = 0
     *
     * (1500100180,古金鹏,24,男,理科一班,445) 1
     * (1500100461,翟凌寒,21,女,理科一班,445) 1
     * (1500100070,濮佑运,22,男,理科一班,442) 3
     * (1500100531,印涵易,22,女,理科一班,440) 4
     * (1500100795,岑浩初,22,男,理科一班,435) 5
     * (1500100869,平紫雪,24,女,理科一班,435) 5
     */

    joinRes
      .groupBy(
        _._5
      )
      .flatMap(
        keyValue => {
          val clazz: String = keyValue._1
          val oneClazzStu: List[(String, String, Int, String, String, Int)] = keyValue._2

          // 需要对相同班级中的数据，添加排名列

          var rank: Int = 0
          var score: Int = 0
          var cnt: Int = 0
          oneClazzStu
            // 以成绩进行倒序排序
            .sortBy(-_._6)
            .map(
              oneStu => {
                // 1.如果成绩相同，那么表示排名一致 对cnt累加1
                // 2.如果成绩不同，那么对rank进行加cnt加1 同时score从新赋值
                if(oneStu._6 == score) {
                  cnt += 1
                  (oneStu._1, oneStu._2, oneStu._3, oneStu._4, oneStu._5, oneStu._6, rank)
                }else{
                  rank += (1+cnt)
                  score = oneStu._6
                  cnt = 0
                  (oneStu._1, oneStu._2, oneStu._3, oneStu._4, oneStu._5, oneStu._6, rank)
                }
              }
            )
//          (clazz, oneClazzStu)
        }
      ).foreach(println)





    //      .filter(_._1 == "理科一班")
    //      .flatMap(_._2)
    //      .toList
    //      .sortBy(-_._6)
    //      .foreach(println)


  }
}
